package cn.buk.qms.web;

import cn.buk.api.wechat.dto.WxData;
import cn.buk.api.wechat.service.WeixinService;
import cn.buk.common.util.DateUtil;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import static cn.buk.qms.HttpServletUtil.sendResponse;

/**
 * 微信服务号
 * Created by yfdai on 2017/2/22
 *
 * @author yfdai
 */
@Profile({"weixin-service"})
@Controller
public class WeixinServiceNoController extends BaseController {

  private static final Logger logger = LogManager.getLogger(WeixinServiceNoController.class);

  @Autowired
  private WeixinService weixinService;


  /**
   * 微信公众号消息转发的地址
   * 加密/校验流程如下：
   * 1. 将token、timestamp、nonce三个参数进行字典序排序
   * 2. 将三个参数字符串拼接成一个字符串进行sha1加密
   * 3. 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
   *
   * @return
   */
  @RequestMapping("/wx-service/{id}")
  public void weixinVerify(HttpServletRequest request, HttpServletResponse response,
                           @PathVariable("id") final int enterpriseId,
                           @RequestParam(value = "signature") final String signature,
                           @RequestParam(value = "timestamp") final String timestamp,
                           @RequestParam(value = "nonce") final String nonce,
                           @RequestParam(value = "echostr", required = false) String echostr) {
    boolean msgFromWeixin = weixinService.verifyWeixinSource(enterpriseId, signature, timestamp, nonce);
    logger.debug("Is this message from weixin? " + signature + ", " + timestamp + ", " + nonce + ", " + echostr + ": " + msgFromWeixin);

    if (!msgFromWeixin) {
      logger.warn("message source is not verified, exit.");
      return;
    }

    /**
     * 验证消息
     */
    if (echostr != null && echostr.length() > 0) {
      logger.debug(echostr);
      sendResponse(response, echostr);

      return;
    }

    final String requestXml = this.readInputXml(request);
    logger.debug("request xml: " + requestXml);

    WxData rq = WxData.fromXml(requestXml);

    if ("text".equalsIgnoreCase(rq.getMsgType()) ||
            "image".equalsIgnoreCase(rq.getMsgType()) ||
            "voice".equalsIgnoreCase(rq.getMsgType())
    ) {

      //weixinService.createWeixinAccessTime(rq.getFromUserName());
      // 转发消息给客服系统
      WxData rs = new WxData();
      rs.setMap("ToUserName", rq.getFromUserName());
      rs.setMap("FromUserName", rq.getToUserName());
      rs.setMap("CreateTime", DateUtil.getCurDateTime().getTime() / 1000);
      rs.setMap("MsgType", "transfer_customer_service");

      String xml = rs.toXml();
      logger.debug(xml);

      sendResponse(response, xml);

      return;
    }

    sendResponse(response, "success"); // 向微信服务器发送 success, 稍后用客服消息发送结果给客户

    if ("event".equalsIgnoreCase(rq.getMsgType())) {
//      weixinService.processWeixinEvent(enterpriseId, response, rq);

      return;
    }
  }
}
